package com.example.demo.pyhelper;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.python.core.PyException;
import org.python.util.PythonInterpreter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by zhangqidzq on 2017/9/10.
 */
@RestController
@RequestMapping("pyhelper")
public class PyhelperRest {

    private PythonInterpreter pythonInterpreter = new PythonInterpreter();

    @RequestMapping(value = "exec", method = RequestMethod.POST)
    public String exec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        initContainer();
        String script = requestParser(request);
        Writer writer = new StringWriter();
        try {
            pythonInterpreter.setOut(writer);
            pythonInterpreter.exec(script);
        } catch (PyException e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            return e.value.toString();
        }
        response.setStatus(HttpServletResponse.SC_OK);
        return writer.toString();
    }

    private String requestParser(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        char[] buf = new char[512];
        int len = 0;
        StringBuffer contentBuffer = new StringBuffer();
        while ((len = reader.read(buf)) != -1) {
            contentBuffer.append(buf, 0, len);
        }
        String content = contentBuffer.toString();
        return content;
    }


    private void initContainer() {
        pythonInterpreter.exec("from com.example.demo.pyhelper import ApplicationContextHolder");
        pythonInterpreter.exec("ioc = ApplicationContextHolder.getApplicationContext()");
        pythonInterpreter.exec("beans = ioc.getBeanDefinitionNames()");
    }
}
